package com.fary.boot;

import com.fary.context.ApplicationListener;
import com.fary.context.event.ContextRefreshedEvent;
import com.fary.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * 清空缓存应用监听器。该监听器的作用是，当接收到上下文刷新事件时，清空当前线程的缓存。
 */
class ClearCachesApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ReflectionUtils.clearCache();
        clearClassLoaderCaches(Thread.currentThread().getContextClassLoader());
    }

    private void clearClassLoaderCaches(ClassLoader classLoader) {
        if (classLoader == null) {
            return;
        }
        try {
            Method clearCacheMethod = classLoader.getClass().getDeclaredMethod("clearCache");
            clearCacheMethod.invoke(classLoader);
        } catch (Exception ex) {
            // Ignore
        }
        clearClassLoaderCaches(classLoader.getParent());
    }

}